<?php
namespace app\backstage\logic;
use think\Db;

class BackhaulLog
{
    public function getList($params)
    {

        $field = 'id,uid,bl_id,request_data,response,create_time,type';

        if (request()->_role->alias == 'agent') {
            $channel_ids = Db::table('cms_manager_user')->where('parent_id', '=', request()->_user->id)
                ->column('id');
            $params['channel_id'] = $channel_ids ? $channel_ids : [0];
        }
        if (request()->_role->alias == 'channel') {
            $params['channel_id'] = request()->_user->id;
        }

        $condition[] = ['channel_id', 'in', 'not_empty', 'channel_id'];
        $condition[] = ['bl_id', 'eq', 'gt:0', 'bl_id'];
        $condition[] = ['uid', 'eq', 'gt:0', 'uid'];
        $condition[] = ['type', 'eq', 'gt:0', 'type'];
        $where = buildQueryCondition($condition, $params);

        if(isset($params['date_range']) && strlen($params['date_range']) > 1)
        {
            list($start_date,$end_date) = explode('~',$params['date_range']);
            $where[] = ['create_time','>=',trim($start_date)." 00:00:00"];
            $where[] = ['create_time','<=',trim($end_date)." 23:59:59"];
        }

        if( isset($params['field']) ){
            $orderBy = [ $params['field'] => $params['order'] ];
        }else{
            $orderBy = ['id' => 'DESC'];
        }

        $Log   = \think\facade\App::model('BackhaulLog');
        $list  = $Log->getList($where, $field, $params['page'], $params['limit'], $orderBy, 'uid,type');

        if($list)
        {
            foreach ($list as $k=>$v)
            {
                $list[$k]['type'] = getBackhaulTypeTitle($v['type']);
            }
        }

        $result['count'] = $Log->getTotalNumber($where,'uid,type');
        $result['list']  = $list;

        return $result;
    }
}